package com.perceptivesoftware.licensing.dao;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import com.perceptivesoftware.licensing.dao.generated.TwUservalDAO;
import com.perceptivesoftware.licensing.domain.generated.TwUserval;
import com.perceptivesoftware.licensing.server.util.EntityUtils;

@Repository
public class TwUservalDaoExt extends TwUservalDAO
{

	/**
	 * Returns all uservals for a user name that are not deleted.
	 * 
	 * @param username
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TwUserval> findAllNotDeletedUservalsForUserName(final String username)
	{
		logger.debug("Finding TwUservals for username: " + username.toUpperCase());
		try
		{
			final String queryString = "select model from TwUserval model where model.uservalUserName = :username and (model." + USERVAL_DELETED + " is null or model." + USERVAL_DELETED + " != 'Y')";
			final Query query = entityManager.createQuery(queryString);
			query.setParameter("username", username.toUpperCase());
			return EntityUtils.getNotDeletedUservals(query.getResultList());
		}
		catch (final RuntimeException re)
		{
			logger.error("get TwUservals by user name failed", re);
			throw re;
		}
	}

	public TwUserval getDefaultUservalForUsername(String username)
	{
		List<TwUserval> users = findAllNotDeletedUservalsForUserName(username);
		if (users != null && users.size() > 0)
		{
			return users.get(0);
		}
		else
		{
			return null;
		}
	}

	public List<TwUserval> getNotDeletedUservals()
	{
		final ArrayList<TwUserval> ret = new ArrayList<TwUserval>();
		for (final TwUserval user : findAll())
		{
			final String deleted = user.getUservalDeleted();
			if (deleted == null || deleted.length() == 0) // modified to exclude
			// "P"
			{
				ret.add(user);
			}
		}
		return ret;
	}

	/**
	 * Returns all uservals for a user name that are not deleted.
	 * 
	 * @param username
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TwUserval> findAllNotDeletedWithEmails()
	{
		logger.debug("Finding TwUservals with not null emails");
		try
		{
			final String queryString = "select model from TwUserval model where model.uservalEmail is not null and (model." + USERVAL_DELETED + " is null or model." + USERVAL_DELETED + " != 'Y')";
			final Query query = entityManager.createQuery(queryString);
			return EntityUtils.getNotDeletedUservals(query.getResultList());
		}
		catch (final RuntimeException re)
		{
			logger.error("get TwUservals with not null emails failed", re);
			throw re;
		}
	}

	public TwUserval update(final TwUserval entity, final TwUserval modifyingUser)
	{
		entity.setUservalDateModified(new Timestamp((new Date()).getTime()));
		entity.setTwUservalByUservalModifiedBy(modifyingUser);
		return update(entity);
	}

	public void save(final TwUserval entity, final TwUserval creatingUser)
	{
		entity.setUservalDateCreated(new Timestamp((new Date()).getTime()));
		entity.setTwUservalByUservalCreatedBy(creatingUser);
		save(entity);
	}

	public void updateUserSettings(final String username, String email)
	{
		final StringBuffer sb = new StringBuffer();
		sb.append("update TwUserval l set l.uservalEmail = :email WHERE l.uservalUserName = :user");
		final Query query = entityManager.createQuery(sb.toString());
		query.setParameter("email", email);
		query.setParameter("user", username);
		query.executeUpdate();
	}
}
